<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 15/06/11
 * Time: 18:11
 * To change this template use File | Settings | File Templates.
 */
 require_once(Config::acquire('SQL.Result',APPLICATION));
class SQL
{


    private static $connection;
    private static $database;

    private static $executed_querys;

    public static function connect($host = '', $user = '', $pass = '', $database = '')
    {
        if (!empty($host) && !empty($user)) {
            self::connectdb($host, $user, $pass);

        }
        if (!empty($database)) {
            self::select_database($database);
        }
        if (!empty($host) && !empty($user) && !empty($database)) {
            mysql_query("SET SESSION sql_mode = 'ANSI,ONLY_FULL_GROUP_BY'", self::connection);
        }
    }

    public static function disconnect()
    {
        mysql_close(self::$connection);
    }


    private static function connectdb($host, $user, $pass = '')
    {
        self::$connection = mysql_connect($host, $user, $pass);
        if (!self::$connection) {
           throw new Exception('Could not connect to MYSQL Server');


        }
    }

    public static function select_database($database_name)
    {
        if (!empty($database_name)) {
            if (empty(self::$database)) {
                self::$database = $database_name;
            }
            if (!mysql_select_db($database_name, self::$connection)) {
                throw new Exception('Could not select database');
            }
        }
    }

    public static function execute($query)
    {
        if (!mysql_query($query, self::$connection)) {
            throw new Exception("could not execute the query");
        }
        self::$executed_querys++;
        return mysql_affected_rows(self::$connection);
    }

    public static function query($query)
    {
        if (!$result = mysql_query($query, self::$connection)) {
            throw new Exception("could not execute the query");
        }
        self::$executed_querys++;
        require_once(Config::acquire('SQL.Result', APPLICATION));
        return new SQL_Result($result);
    }

    public static function getTotalQuerys()
    {
        return self::$executed_querys;
    }


    public static function getConnection()
    {
        return self::$connection;
    }

    public static function getDatabase()
    {
        return self::$database;
    }
}
